#include "stdafx.h"
#include "threadpool.h"

namespace natrium {
	namespace util {
		ThreadPool::ThreadPool(Task t, unsigned int numThreads):
			mCompleted(false)
		{
			if (numThreads == 0)
				numThreads = std::thread::hardware_concurrency();

			for (size_t i = 0; i < numThreads; ++i)
				mPool.push_back(std::thread(t));
		}

		ThreadPool::~ThreadPool() {
			if (!mCompleted)
				join();
		}

		void ThreadPool::join() {
			std::for_each(
				mPool.begin(),
				mPool.end(),
				[](std::thread& t) {
					t.join();
				}
			);

			mCompleted = true;
		}

		void ThreadPool::detachAll() {
			std::for_each(
				mPool.begin(),
				mPool.end(),
				[](std::thread& t) {
					t.detach();
				}
			);

			mCompleted = true;
		}
	}
}